package com.atguigu.gmall.payment.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeCloseRequest;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeCloseResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.atguigu.gmall.model.enums.PaymentStatus;
import com.atguigu.gmall.model.enums.PaymentType;
import com.atguigu.gmall.model.enums.PaymentWay;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.model.payment.PaymentInfo;
import com.atguigu.gmall.order.client.OrderFeignClient;
import com.atguigu.gmall.payment.config.AlipayConfig;
import com.atguigu.gmall.payment.service.AlipayService;
import com.atguigu.gmall.payment.service.PaymentService;
import com.google.common.collect.Ordering;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * @author atguigu-mqx
 */
@Service
public class AlipayServiceImpl implements AlipayService {

    @Autowired
    private PaymentService paymentService;

    @Autowired
    private OrderFeignClient orderFeignClient;

    @Autowired
    private AlipayClient alipayClient;

    @Override
    public String createAlipay(Long orderId) throws AlipayApiException {
        //  根据订单Id 来获取订单对象。
        OrderInfo orderInfo = this.orderFeignClient.getOrderInfo(orderId);
        //  判断订单如何是取消或已支付，则不能生产二维码！
        if ("CLOSED".equals(orderInfo.getOrderStatus()) || "PAID".equals(orderInfo.getOrderStatus())){
            return "当前订单已关闭或已支付!";
        }
        //  保存支付交易记录
        this.paymentService.savePaymentInfo(orderInfo, PaymentType.ALIPAY.name());

        //  获取到alipayClient 对象。 固定值：默认网关，电脑网站支付对应appId ,私钥，格式，Json ，字符集 utf-8 ,公钥， 签名算法类型 推荐RSA2
        //  将这个对象注入到spring 容器中...
        //  AlipayClient alipayClient =  new DefaultAlipayClient( "https://openapi.alipay.com/gateway.do" , APP_ID, APP_PRIVATE_KEY, FORMAT, CHARSET, ALIPAY_PUBLIC_KEY, SIGN_TYPE);  //获得初始化的AlipayClient
        AlipayTradePagePayRequest alipayRequest =  new  AlipayTradePagePayRequest(); //创建API对应的request
        //  设置同步回调地址 http://api.gmall.com/api/payment/alipay/callback/return
        alipayRequest.setReturnUrl(AlipayConfig.return_payment_url);
        //  设置异步回调地址
        alipayRequest.setNotifyUrl(AlipayConfig.notify_payment_url); //在公共参数中设置回跳和通知地址
        //  参数
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("out_trade_no",orderInfo.getOutTradeNo());
        jsonObject.put("product_code","FAST_INSTANT_TRADE_PAY");
        jsonObject.put("total_amount","0.01");
        jsonObject.put("subject",orderInfo.getTradeBody());
        //  二维码的有效期！time_expire 绝对超时时间。
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        /*
            case1: 过期时间设置 10m

            订单过期时间是24小时 ；  还剩1分钟，扫描支付。
                订单要是取消了：
                    允许支付成功： 后续通过异步回调更改掉订单的状态.
                    不允许支付成功：
                        1.  设置二维码的过期时间与订单过期时间一样.
                        2.  用二维码的有效时间与订单过期时间做比较.  过期时间大于订单的失效时间，设置订单的失效时间为二维码的过期时间。
         */
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE,2);
        jsonObject.put("time_expire",simpleDateFormat.format(calendar.getTime()));
        alipayRequest.setBizContent(jsonObject.toJSONString());
        return alipayClient.pageExecute(alipayRequest).getBody();  //调用SDK生成表单
    }

    /**
     * 退款全部金额.
     * @param orderId
     * @return
     */
    @Override
    public Boolean refund(Long orderId) {
        //  根据orderId 来获取OrderInfo
        OrderInfo orderInfo = orderFeignClient.getOrderInfo(orderId);
        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", orderInfo.getOutTradeNo());
        bizContent.put("refund_amount", 0.01);
        bizContent.put("out_request_no", "HZ01RF001");

        request.setBizContent(bizContent.toString());
        AlipayTradeRefundResponse response = null;
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        if(response.isSuccess()){
            System.out.println("调用成功");
            //  更新交易记录状态.
            PaymentInfo paymentInfo = new PaymentInfo();
            paymentInfo.setPaymentStatus(PaymentStatus.CLOSED.name());
            this.paymentService.updatePaymentInfo(orderInfo.getOutTradeNo(),PaymentType.ALIPAY.name(),paymentInfo);
            return true;
        } else {
            System.out.println("调用失败");
            return false;
        }
    }

    @Override
    public Boolean closePay(Long orderId) {
        //  查询orderInfo
        OrderInfo orderInfo = this.orderFeignClient.getOrderInfo(orderId);
        //  关闭接口.
        AlipayTradeCloseRequest request = new AlipayTradeCloseRequest();
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", orderInfo.getOutTradeNo());
        request.setBizContent(bizContent.toString());
        AlipayTradeCloseResponse response = null;
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        if(response.isSuccess()){
            System.out.println("调用成功");
            return true;
        } else {
            System.out.println("调用失败");
            return false;
        }
    }

    @Override
    public Boolean checkPayment(Long orderId) {
        //  查询orderInfo
        OrderInfo orderInfo = this.orderFeignClient.getOrderInfo(orderId);
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", orderInfo.getOutTradeNo());
        request.setBizContent(bizContent.toString());
        AlipayTradeQueryResponse response = null;
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

        if(response.isSuccess()){
            System.out.println("调用成功");
            return true;
        } else { // !response.isSuccess() || response.getTradeStatus().equals(close);
            System.out.println("调用失败");
            return false;
        }
    }

}
